﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lm.Common.ExtensionMethods;

namespace Lm.Common.Security.Cryptography
{
    public class AesCrypto
    {
        public AesCrypto(byte[] key, byte[] iv)
        {
            //if (key.Length != 32)
            //{ throw new Exception("密钥必须为32字节"); }
            //if (iv.Length != 16)
            //{ throw new Exception("向量必须为16字节"); }
            this.Key = key;
            this.IV = iv;
        }
        
        protected byte[] Key
        { get; set; }
        protected byte[] IV
        { get; set; }

        public string EncryptToBase64String(string str)
        {
            byte[] buf = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] bResult = this.Encrypt(buf);
            string result = Convert.ToBase64String(bResult);
            return result;
        }
        public byte[] Encrypt(byte[] buf)
        {
            using (var aes = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                using (var encryptor = aes.CreateEncryptor(this.Key, this.IV))
                {
                    using (var ms = new System.IO.MemoryStream())
                    {
                        using (var encryptStream = new System.Security.Cryptography.CryptoStream(ms, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            encryptStream.Write(buf, 0, buf.Length);
                            encryptStream.Flush();
                            encryptStream.FlushFinalBlock();
                            return ms.ToArray();
                        }
                    }
                }
            }
        }

        public string DecryptFromBase64String(string str)
        {
            byte[] buf = Convert.FromBase64String(str);
            byte[] bResult = this.Decrypt(buf);
            string result = System.Text.Encoding.UTF8.GetString(bResult);
            return result;
        }
        public byte[] Decrypt(byte[] buf)
        {
            using (var ms = new System.IO.MemoryStream(buf))
            {
                using (var aes = new System.Security.Cryptography.AesCryptoServiceProvider())
                {
                    using (var decryptor = aes.CreateDecryptor(this.Key, this.IV))
                    {
                        using (var decryptStream = new System.Security.Cryptography.CryptoStream(ms, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                        {
                            return decryptStream.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
}


